
$("#subBtn").click(function () {
    makeLoveLetter();
});
$("#previewBtn").click(function () {
    previewUser();
});
$("#secret input:radio").change(function() {
    var $this = $(this);
    var value = $this.val();
    if (value == "-1") {
        $("#inputPwdDiv").show();
    } else {
        $("#inputPwdDiv").hide();
    }
});

function previewUser() {
    var userWord = {};
    var status = 1;
    $(".form-horizontal").find("input[name='fields'],textarea[name='fields']").each(function(){
        var $this = $(this);
        var id = $this.attr("id");
        var value = $this.val();
        if (value == "") {
            status = 0;
            Toast("请先填写完整信息", 3000);
            return;
        }
        userWord[id] = value;
    });
    if (status == 0) {
        return;
    }
    var parames = new Array();
    parames.push({ name: "id", value: loveLetterId});
    parames.push({ name: "user_word", value: JSON.stringify(userWord)});
    Post("/preview/user", parames);
}

function makeLoveLetter() {
    var userWord = {};
    var status = 1;
    $(".form-horizontal").find("input[name='fields'],textarea[name='fields']").each(function(){
        var $this = $(this);
        var id = $this.attr("id");
        var value = $this.val();
        if (value == "") {
            status = 0;
            Toast("请先填写完整信息", 4000);
            return;
        }
        userWord[id] = value;
    });
    var secret = $("#secret input:radio:checked").val();
    var dataObj = {
        "expression_templates_id":loveLetterId,
        "user_word":JSON.stringify(userWord),
        "secret": secret,

    };
    if (secret == "-1") {
        var pwd = $("#pwd").val();
        if (pwd == "" || pwd == undefined || pwd == null || !/\d{1,6}/.test(pwd)) {
            Toast("请先输入密码，最长6位数", 4000);
            return;
        }
        dataObj["pwd"] = pwd;
    }

    $.ajax({
        type : "POST",
        url : "/love-letter/add",
        data : dataObj,
        //请求成功
        success : function(result) {
            if(result.code==1) {
                // 注册页面跳转，返回首页
                window.location.href ="/love/you?i=" + result.data;
            } else if (result.code == -10) {
                Toast("请先登录", 3000);
            }else {
                Toast(result.msg, 3000);
            }
        },
        //请求失败，包含具体的错误信息
        error : function(e){
            $("#error").html("操作失败！");
            console.log(e.responseText);
        }
    });
}

function Toast(msg,duration){
    duration=isNaN(duration)?3000:duration;
    var m = document.createElement('div');
    m.innerHTML = msg;
    m.style.cssText="max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 10%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
    document.body.appendChild(m);
    setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
        setTimeout(function() { document.body.removeChild(m) }, d * 1000);
    }, duration);
}

/* bootstrap开关控件，初始化 */
$(function(){
    /* 初始化控件 */
    $(".checkbox").bootstrapSwitch({
        onText : "开",      // 设置ON文本
        offText : "关",    // 设置OFF文本
        onColor : "success",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor : "danger",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size : "normal",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth:"35",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange : function(event, state) {
            var ProductId = event.target.defaultValue;
            if (state == true) {
                //上线
            } else {
                //下线
            }
        }
    });
});

/*
    *功能： 模拟form表单的提交
    *参数： URL 跳转地址 PARAMTERS 参数
    */
function Post(URL, PARAMTERS) {
    //创建form表单
    var temp_form = document.createElement("form");
    temp_form.action = URL;
    //如需打开新窗口，form的target属性要设置为'_blank'
    temp_form.target = "_blank";
    temp_form.method = "post";
    temp_form.style.display = "none";
    //添加参数
    for (var item in PARAMTERS) {
        var opt = document.createElement("textarea");
        opt.name = PARAMTERS[item].name;
        opt.value = PARAMTERS[item].value;
        temp_form.appendChild(opt);
    }
    document.body.appendChild(temp_form);
    //提交数据
    temp_form.submit();
}

$.ajax({
    type: "GET",
    url: "/web/login-status",
    dataType: "JSON",
    //请求成功
    success: function (result) {
        if (result.code != 1) {
            Toast("请先登录", 3000);
        }
    },
    //请求失败，包含具体的错误信息
    error: function (e) {
    }
});

function getQueryVariable(variable)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return null;
}
var id = null;
function dealUpdate() {
    id = getQueryVariable("id");
    if(id == null) {
        return;
    }
    $.ajax({
        type : "GET",
        url : "/love-letter/user_word",
        data : {
            "id": id,
        },
        success : function(result) {
            if(result.code==1) {
                console.log(result.data);
                var data = null;
                for (var i = 0, len = result.data.length; i < len; i++) {
                    data = result.data[i];
                    $("#"+ data["expression_templates_field_id"]).val(data["word"].replace(/\<br\/\>/g, "\n"));
                }
            }
        }
    });
}
dealUpdate();
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//执行一个laydate实例
laydate.render({
    elem: '.datea', //指定元素
    type: 'datetime',
    position: 'fixed',
    max: new Date().format("yyyy-MM-dd HH:mm:ss")
});
console.log(new Date().format("yyyy-MM-dd HH:mm:ss"))

